package worst.shopping.lists;

import database.DataBaseKeys;
import database.ListDAO;
import worst.shopping.R;
import worst.shopping.products.EditProductActivity;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.*;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

public class ListViewActivity extends ListActivity {
	private String _listName;
	private Cursor _cursor;
	private Float _totalPrice;
	private ListDAO _listDAO;
	private ListViewHighlightableImageCursorAdapter _adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.shoppinglistview);
		_listName = getIntent().getExtras().getString(DataBaseKeys.LIST_NAME);
		_listDAO = new ListDAO(getApplication());
//		_cursor = _listDAO.getItemsForList(_listName);
		
		
		registerForContextMenu(getListView());
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		_cursor = _listDAO.getItemsForList(_listName);
		startManagingCursor(_cursor);
		
		_adapter = new ListViewHighlightableImageCursorAdapter(this, 
				R.layout.listitem_withextra, 
				_cursor, 
				new String[] { DataBaseKeys.PRODUCT_NAME, DataBaseKeys.PRODUCT_ICON }, 
				new int[]{ R.id.list_item_name, R.id.list_item_image},
				getResources().getDrawable(R.drawable.gradient), 
				_listDAO, 
				_listName);	
		
		_adapter.setListName(_listName);
		
		setUpListView();
		setTitleText();

	}
	
	private void setTitleText() {
		_totalPrice = calculateTotalListPrice();
		
		TextView listNameLabel = (TextView)findViewById(R.id.ShoppingListNameLabel);
		listNameLabel.setText(_listName + " ("+_totalPrice+")");
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		
		super.onCreateContextMenu(menu, v, menuInfo);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.listview_contextmenu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	 
	  _cursor.moveToPosition(info.position);
	  String productName = _cursor.getString(_cursor.getColumnIndex(DataBaseKeys.PRODUCT_NAME));
	  
	  switch (item.getItemId()) {
	  	case R.id.edit_product:
	  		Intent intent = new Intent(this, EditProductActivity.class);
	  		intent.putExtra(DataBaseKeys.PRODUCT_NAME, productName);
	  		startActivity(intent);
	  		break;
	  	case R.id.remove_product:
	  		_listDAO.removeListEntry(_listName, productName);
	  		_cursor.requery();
	  		setTitleText();
	  		break;
	  	default:
	  		return super.onContextItemSelected(item);
	  }	  
	  
	  return true;
	}
	
	private Float calculateTotalListPrice() {
		//get price and amount for each product
		Float totalPrice = 0.0F;
		
		_cursor.moveToFirst();
		do
		{
			int amount = _cursor.getInt(_cursor.getColumnIndex(DataBaseKeys.PRODUCT_COUNT));
			float price = _cursor.getFloat(_cursor.getColumnIndex(DataBaseKeys.PRODUCT_PRICE));
			
			totalPrice += (amount * price);
		}while(_cursor.moveToNext());
		
		return totalPrice;
	}

	private void setUpListView() {
		ListView listView = getListView();
		listView.setAdapter(_adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> adapterview, View view, int pos,
					long id) {
				_cursor.moveToPosition(pos);
				
				String productname = _cursor.getString(_cursor.getColumnIndex(DataBaseKeys.PRODUCT_NAME));
				//remove selection
				if(_listDAO.isSelected(_listName, productname))
				{
					_listDAO.markListEntry(_listName, _cursor.getString(_cursor.getColumnIndex(DataBaseKeys.PRODUCT_NAME)), false);	        
				}
				else
				{
	        	    _listDAO.markListEntry(_listName, _cursor.getString(_cursor.getColumnIndex(DataBaseKeys.PRODUCT_NAME)), true);
				}
				
	        	_adapter.notifyDataSetChanged();	 
			}
		});					
	}

	public void saveListAndLeaveActivityButton(View view)
	{
		finish();
	}
	
	public void addProductToListButton(View view)
	{
		Intent intent = new Intent(this, EditListActivity.class);
		intent.putExtra(DataBaseKeys.LIST_NAME, _listName);
		startActivityForResult(intent, 0);			
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == 0)
		{
			if(resultCode == Activity.RESULT_OK)
			{
				String newListName = data.getExtras().getString(DataBaseKeys.LIST_NAME);
				_listName = newListName;			
			}
		}
		
	}
}
